#!/bin/bash
#
# Copyright 2018-2021 Balena Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

. /usr/libexec/os-helpers-logging
# shellcheck disable=SC1091
. /usr/sbin/balena-config-vars

nm_conf_fragment=/etc/NetworkManager/conf.d/os-networkmanager.conf

# This defines config.json to NetworkManager values
value_map='true=yes false=no'

# Returns the value of a key in a map variable
# The map needs to be a space separated set of entries. Each key/value pair separated by '='
# Returns:
# 	If key exists in map: the value in 'value' variable.
# 	If key not found: returns the key in 'value' variable.
getValueInMap() {
	local key="$1"
	local map="$2"
	# shellcheck disable=SC2001
	value="$(echo "$map" | sed -e "s/.*${key}=\([^ ]*\).*/\1/")"
	if [ "$value" = "$map" ]; then
		value="$key"
	fi
}

#
# MAIN
#

if [ ! -f "$CONFIG_PATH" ]; then
	fail "$CONFIG_PATH does not exist."
else
	info "Found config.json in $CONFIG_PATH ."
fi

# shellcheck disable=SC2153
if [ -n "$NM_CONF_FRAGMENT" ]; then
	nm_conf_fragment="$NM_CONF_FRAGMENT"
fi
info "Using NetworkManager configuration fragment file in $nm_conf_fragment."

nm_config="# This file is generated based on os.networkManager configuration in config.json."

# [device]
if [ "$OS_NET_WIFI_MACSCAN" != "null" ]; then
	info "Found randomMacAddressScan configuration."
	getValueInMap "$OS_NET_WIFI_MACSCAN" "$value_map"
	nm_config+=$(echo -e "\n\n[device]")
	nm_config+=$(echo -e "\nwifi.scan-rand-mac-address=${value}")
fi

# [connectivity]
disable_connectvity_check=0

if [ -n "$OS_NET_CONN_URI" ] ; then
	if [ "$OS_NET_CONN_URI" = "$API_ENDPOINT/connectivity-check" ]; then
		info "Connectivity URI not defined. Using default."
	fi
else
	disable_connectvity_check=1
	info "API_ENDPOINT not defined. Disabling connectivity check."
fi

if [ "$disable_connectvity_check" -eq 0 ]; then
	info "Using connectivity URI      : $OS_NET_CONN_URI"
	info "Using connectivity interval : $OS_NET_CONN_INTERVAL"
	info "Using connectivity response : \"${OS_NET_CONN_RESPONSE}\""
	nm_config+=$(echo -e "\n\n[connectivity]")
	nm_config+=$(echo -e "\nuri=${OS_NET_CONN_URI}")
	nm_config+=$(echo -e "\ninterval=${OS_NET_CONN_INTERVAL}")
	nm_config+=$(echo -e "\nresponse=${OS_NET_CONN_RESPONSE}")
fi

# Write final NM configuration fragment
if [ ! -f "$nm_conf_fragment" ] || [ "$(cat \
	"$nm_conf_fragment")" != "$nm_config" ]; then
	info "Writing/initialiazing custom NM configuration."
	echo "$nm_config" > "$nm_conf_fragment.tmp"
	sync -f "$nm_conf_fragment.tmp"
	mv "$nm_conf_fragment.tmp" "$nm_conf_fragment"
else
	info "NM custom configuration fragment already in place."
fi
